package com.bong.panpan.bongcharttools;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;

import com.bong.panpan.bongcharttools.activity.UserListActivity;
import com.bong.panpan.bongcharttools.custom.Constant;
import com.bong.panpan.bongcharttools.custom.MyUtil;
import com.bong.panpan.bongcharttools.custom.SpUtil;
import com.bong.panpan.bongcharttools.custom.UserInfoRecord;
import com.bong.panpan.bongcharttools.fragment.BleServerSettingFragment;
import com.bong.panpan.bongcharttools.fragment.ChartListContents;
import com.bong.panpan.bongcharttools.fragment.ChartListFragment;
import com.bong.panpan.bongcharttools.util.Common;
import com.bong.panpan.bongcharttools.util.PermissionRequireActivity;
import com.bong.panpan.bongcharttools.view.MyDialog;
import com.github.mikephil.charting.charts.LineChart;

import java.io.File;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

/**
 * Created by panpan on 2017/9/26.
 */

public class MainActivity2 extends PermissionRequireActivity implements
        DrawerLayout.DrawerListener,
        ChartListFragment.OnListFragmentInteractionListener,
        BleServerSettingFragment.OnFragmentInteractionListener {
    @InjectView(R.id.chart1)
    LineChart chart1;
    @InjectView(R.id.begin_btn)
    Button beginBtn;
    @InjectView(R.id.save_btn)
    Button saveBtn;
    @InjectView(R.id.value_check)
    CheckBox valueCheck;
    @InjectView(R.id.circle_check)
    CheckBox circleCheck;
    @InjectView(R.id.high_light_check)
    CheckBox highLightCheck;
    @InjectView(R.id.line_check1)
    CheckBox lineCheck1;
    @InjectView(R.id.line_check2)
    CheckBox lineCheck2;
    @InjectView(R.id.mode_spinner)
    Spinner modeSpinner;
    @InjectView(R.id.scan_btn)
    Button scanBtn;
    @InjectView(R.id.refresh_btn)
    Button refreshBtn;
    @InjectView(R.id.radioButton3)
    RadioButton radioButton3;
    @InjectView(R.id.radioButton2)
    RadioButton radioButton2;
    @InjectView(R.id.radioButton1)
    RadioButton radioButton1;
    @InjectView(R.id.rssi_radio)
    RadioGroup rssiRadio;
    @InjectView(R.id.filter_edit)
    EditText filterEdit;
    @InjectView(R.id.cls_btn)
    Button clsBtn;
    @InjectView(R.id.device_list)
    ListView deviceList;
    @InjectView(R.id.drawer_layout)
    DrawerLayout drawerLayout;
    @InjectView(R.id.link_info)
    TextView linkInfo;
    @InjectView(R.id.clear_btn)
    Button clearBtn;
    @InjectView(R.id.load_btn)
    Button loadBtn;
    @InjectView(R.id.text_value)
    TextView textValue;
    @InjectView(R.id.text_value2)
    TextView textValue2;
    @InjectView(R.id.text_value3)
    TextView textValue3;
    @InjectView(R.id.text_user_name)
    TextView textUserName;
    @InjectView(R.id.text_time)
    TextView textTime;

    private DeviceSelectHelper deviceSelectHelper;
    private ChartShowHelper2 chartShowHelper;
    private ChartListFragment chartListFragment;
    private String userName, userPath;
    private UserInfoRecord record;
    private MyDialog myDialog;
    //private BleServerSettingFragment bleSetFragment;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SpUtil.getInstance().init(getApplicationContext());
        setContentView(R.layout.activity_main2);
        ButterKnife.inject(this);
        if (deviceList == null) {
            Common.showToast(this, "deviceList==null");
            return;
        }
        deviceSelectHelper = new DeviceSelectHelper(
                scanBtn,
                refreshBtn,
                radioButton3,
                radioButton2,
                radioButton1,
                rssiRadio,
                filterEdit,
                clsBtn,
                deviceList,
                linkInfo,
                handler,
                this);
        chartShowHelper = new ChartShowHelper2(
                chart1,
                beginBtn,
                saveBtn,
                clearBtn,
                loadBtn,
                new CheckBox[]{valueCheck, circleCheck, highLightCheck, lineCheck1, lineCheck2},
                modeSpinner,
                findViewById(R.id.scroll_layout),
                new TextView[]{textValue, textValue2, textValue3,textTime},
                this);
        deviceSelectHelper.protocol.setListener(chartShowHelper);
        drawerLayout.addDrawerListener(this);
        chartListFragment = ChartListFragment.newInstance(1, 0);
        //bleSetFragment = BleServerSettingFragment.newInstance("", "");
        //getSupportFragmentManager().beginTransaction().replace(R.id.drawer_right, chartListFragment, "chart").commit();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.add(R.id.drawer_right, chartListFragment, "chart");
        //transaction.add(R.id.drawer_right, bleSetFragment, "bleSet");
        transaction.commit();
        //drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, Gravity.RIGHT);
        myDialog=new MyDialog(this);
    }

    @OnClick({R.id.begin_btn, R.id.save_btn, R.id.load_btn, R.id.scan_btn, R.id.refresh_btn, R.id.cls_btn, R.id.clear_btn})
    public void onViewClicked(View view) {
        FragmentTransaction transaction;
        switch (view.getId()) {
            case R.id.begin_btn:
                if (record == null) {
                    MyUtil.showToast(this, "请设置一个用户");
                    startActivityForResult(new Intent(this, UserListActivity.class), 0x01);
                    break;
                }
                chartShowHelper.beginClick(beginBtn);
                break;
            case R.id.clear_btn:
                if (record == null) {
                    MyUtil.showToast(this, "请设置一个用户");
                    startActivityForResult(new Intent(this, UserListActivity.class), 0x01);
                    break;
                }
                myDialog.show(record,null);
                //chartShowHelper.onClearClicked();
                break;
            case R.id.save_btn:
                if (record == null) {
                    MyUtil.showToast(this, "请设置一个用户");
                    startActivityForResult(new Intent(this, UserListActivity.class), 0x01);
                    break;
                }
                chartShowHelper.saveClick(saveBtn);
                break;
            case R.id.load_btn:
                //transaction = getSupportFragmentManager().beginTransaction();
                //transaction.hide(bleSetFragment);
                //transaction.show(chartListFragment);
                //transaction.commit();
                //drawerLayout.openDrawer(Gravity.RIGHT);
                startActivityForResult(new Intent(this, UserListActivity.class), 0x01);
                break;
            case R.id.scan_btn:
                deviceSelectHelper.scanClick(scanBtn);
                break;
            case R.id.refresh_btn:
                deviceSelectHelper.refreshClick(refreshBtn);
                break;
            case R.id.cls_btn:
                deviceSelectHelper.clearClick(clsBtn);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        deviceSelectHelper.onDestory();
        chartShowHelper.onDestory();
        super.onDestroy();
    }

    public DeviceSelectHelper getDeviceSelectHelper() {
        return deviceSelectHelper;
    }

    public ChartListFragment getChartListFragment() {
        return chartListFragment;
    }

    /**
     * Called when a drawer's position changes.
     *
     * @param drawerView  The child view that was moved
     * @param slideOffset The new offset of this drawer within its range, from 0-1
     */
    @Override
    public void onDrawerSlide(View drawerView, float slideOffset) {

    }

    /**
     * Called when a drawer has settled in a completely open state.
     * The drawer is interactive at this point.
     *
     * @param drawerView Drawer view that is now open
     */
    @Override
    public void onDrawerOpened(View drawerView) {
        if (drawerView.getId() != R.id.drawer_right) {
            deviceSelectHelper.beginScan();
        } else {
            //drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, Gravity.RIGHT);
        }
    }

    /**
     * Called when a drawer has settled in a completely closed state.
     *
     * @param drawerView Drawer view that is now closed
     */
    @Override
    public void onDrawerClosed(View drawerView) {
        if (drawerView.getId() != R.id.drawer_right) {
            deviceSelectHelper.stopScan();
        } else {
            //drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, Gravity.RIGHT);
        }
    }

    @Override
    public void onDrawerStateChanged(int newState) {

    }

    AlertDialog deleteDialog;

    private void showDeleteDialog(String msg, AlertDialog.OnClickListener listener) {
        if (deleteDialog == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("提示");
            builder.setPositiveButton("确定", listener);
            builder.setNegativeButton("取消", null);
            deleteDialog = builder.create();
        }
        deleteDialog.setMessage(msg);
        deleteDialog.show();
        deleteDialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(Color.BLUE);
        deleteDialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(Color.RED);
    }

    ChartListContents.ChartListItem deleteChartItem;
    AlertDialog.OnClickListener deleteListener = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            if (new File(deleteChartItem.contentPath).delete()) {
                new File(deleteChartItem.contentPath.replace(Constant.chartEndName,".csv")).delete();
                chartListFragment.refreshList();
                Common.showToast(MainActivity2.this, deleteChartItem.content + "\n已删除");
                deleteChartItem = null;
            } else {
                Common.showToast(MainActivity2.this, deleteChartItem.content + "\n删除失败");
            }
        }
    };

    @Override
    public void onListFragmentInteraction(ChartListContents.ChartListItem item, int id) {
        if (id % 10 == 0) {
            if (chartShowHelper.loadChartData(item.contentPath))
                Common.showToast(this, "读取\"" + item.content + "\"成功");
            else
                Common.showToast(this, "读取\"" + item.content + "\"失败");
        }
        if (id % 10 == 1) {
            deleteChartItem = item;
            showDeleteDialog("确定删除：\"" + item.content + "\"？\n删除后不可恢复，请谨慎操作！", deleteListener);
        }
        if (id % 10 == 2) {
            Intent intent = new Intent(Intent.ACTION_SEND);
            intent.setType("text/plain");
            //intent.setType("image/jpeg");
            intent.putExtra(Intent.EXTRA_TEXT, "PPG ECG 曲线图");
            intent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://"+item.contentPath.replace(Constant.chartEndName,".csv")));
            startActivity(Intent.createChooser(intent, "发送至："));
        }
    }

    @Override
    public void onBleSetFragmentInteraction() {
        drawerLayout.closeDrawer(Gravity.RIGHT);
    }

    long time = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (drawerLayout.isDrawerOpen(Gravity.START) || drawerLayout.isDrawerOpen(Gravity.RIGHT)) {
                drawerLayout.closeDrawers();
                return true;
            }
            if (System.currentTimeMillis() - time > 800) {
                Common.showToast(this, "再按一次退出");
                time = System.currentTimeMillis();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 0x01) {
            if (resultCode == Activity.RESULT_OK) {
                userName = data.getStringExtra("userName");
                userPath = data.getStringExtra("userPath");
                textUserName.setText(userName);
                record = UserInfoRecord.load(userPath);
                chartShowHelper.userInfoRecord = record;
                if (record != null) {
                    MyUtil.showToast(this, "已设置用户为：" + userName);
                }
            } else {
                MyUtil.showToast(this, "未设置用户");
            }
        }
    }
}
